package org.ss.psci.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.ss.psci.entity.*;
import org.ss.psci.util.DateUtil;
import org.ss.psci.util.ListRange;

public class InfoService {
	private BaseDAO baseDAO;
	private List list;

	public ListRange getPmMessages(Map condition) {
		int rows, start, limit;
		try {
			try {
				start = Integer.parseInt(condition.get("start").toString());
				limit = Integer.parseInt(condition.get("limit").toString());
			} catch (Exception ex) {
				start = 0;
				limit = 10;
			}
			if ((list == null) || (start == 0)) {
				list = baseDAO.getPmMessageDAO().findAll();
			}
			if (list == null) {
				ListRange listRange = new ListRange();
				return listRange;
			} else {
				rows = start + limit > list.size() ? list.size() : start
						+ limit;
			}
			List result = new ArrayList();
			for (int i = start; i < rows; i++) {
				result.add(list.get(i));
			}
			ListRange listRange = new ListRange();
			listRange.setData(result.toArray());
			listRange.setTotalSize(list.size());

			return listRange;
		} catch (Exception ex) {
			System.out.println(ex.toString());
			ListRange listRange = new ListRange();
			return listRange;
		}
	}

	public void savePmMessage(String title, Map formMap) {
		PmMessage pu = new PmMessage();
		try {
			BeanUtils.populate(pu, formMap);
			PmMessage p = getPmMessage(title);
			if (p != null) {
				p=baseDAO.getPmMessageDAO().copyEntity(p, pu);
				baseDAO.getPmMessageDAO().save(p);
			} else {
				pu.setCtTime(new DateUtil().toString());
				baseDAO.getPmMessageDAO().save(pu);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void delPmMessage(String title) {
		try {
			PmMessage p = getPmMessage(title);
			if (p != null) {
				baseDAO.getPmMessageDAO().delete(p);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public PmMessage getPmMessage(String title) {
		PmMessage p = new PmMessage();
		List uList = baseDAO.getPmMessageDAO().findByTitle(title);
		if (uList != null) {
			if (uList.size() != 0) {
				p = (PmMessage) uList.get(0);
			}
		}
		return p;
	}

	public BaseDAO getBaseDAO() {
		return baseDAO;
	}

	public void setBaseDAO(BaseDAO baseDAO) {
		this.baseDAO = baseDAO;
	}
}
